let app = getApp();
const { getOpenID } = require('../../../utils/ws/wsxcx-opendata-sdk');
const _util = require('../util.js');

Page({
  _privateData: {
    openID: null,
  },
  data: {
    items: [],
    collectedItems: [],
    toView: '',
    windowHeight: 0,
    loading: true,
  },
  onLoad: function (argument) {
    let that = this;
    let openID = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');

    // this.getUserLocation().then(res => {
    //   this.setData({ userLocation: res }, () => {
    if (!openID) {
      if (app.modules === 'ws_micro_shop') {
        app.ws_micro_shoplogin().then(function() {
          openID = wx.getStorageSync('OPENID');
          that._privateData.openID = openID;
          that.init();
        });
      } else {
        getOpenID().then(openID => {
          that._privateData.openID = openID;
          that.init();
        });
      }
    } else {
      that._privateData.openID = openID;
      this.init();
    }
    //   });
    // });


    wx.getSystemInfo({
      success: res => {
        this.setData({
          windowHeight: res.windowHeight - 55,
        });
      },
    });
    // wx.showLoading();
  },

  onPullDownRefresh(e) {
    this.init();
  },

  getUserLocation() {
    return new Promise(resolve => {
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          app.util.request({
            url: 'card/api/convert',
            data: {
              lat: res.latitude,
              lng: res.longitude,
            },
            success: res => {
              resolve(res.data.data.location);
  },
          });
        },
      });
    });
  },

  init() {
    let that = this;
    app.util.request({
      url: 'card/api/get_service_list',
      data: {
        ...this.data.userLocation,
      },
      showLoading: true,
      cachetime: 30,
      success: res => {
        that.setData({
          items: res.data.data,
          loading: false,
        });
        // wx.hideLoading();
      },
      fail: res => {
        if (Number(res.data.errno) === -1) {
          _util.loginBeforeGetMobile().then(res => {
            res && that.init();
          });
        }
        // wx.hideLoading();
        that.setData({ loading: false });
      },
    });
  },
  gotoMsg(e) {
    const { targetOpenid, period } = e.currentTarget.dataset;
    const { openID } = this._privateData;
    const url = '/common/component/universal-card/pages/message?openid=' + openID + '&to_openid=' + targetOpenid + '&scene=inner&m_id=0';
    // TODO, 判断是否是自己，判断是否在线 如果不在线，删除（动态设置当前时间段）
    // 这里设置下当前时间，wxml动态判断
    // if (period < Date.now()) {
    //   return wx.showToast({

    //   });
    // }
    app.util.navigateTo(url);
  },

  doCall(e) {
    const { phone: phoneNumber, cardid } = e.currentTarget.dataset;
    // const exp = app.util.phoneExp.mobile;
    // 同上，判断是否在线
    if (phoneNumber) {
      wx.makePhoneCall({
        phoneNumber,
        success: res => {
          // TODO, 验证点击号码前还是后调用回调。记录拨号动作 请求接口进行存储。 本人openID 目标人openID 目标电话 当前时间
          res.errMsg === 'makePhoneCall:ok' && app.util.request({
            url: 'card/api/access_log',
            data: {
              pt: getCurrentPages().pop().route,
              pm: getCurrentPages().pop().options,
              cn: 'phone',
              tp: 2,
              card_id: cardid,
            },
          });
        },
      });
    } else {
      wx.showToast({
        title: '该用户没留下手机号码',
        icon: 'none',
      });
    }
  },

  gotoCardDetail(e) {
    const { cardid, targetOpenid } = e.currentTarget.dataset;
    let url;
    if (targetOpenid && cardid) {
      url = `/common/component/universal-card/card-show?openid=${targetOpenid}&cardid=${cardid}`;
    } else {
      url = '/common/component/universal-card/card-preview';
    }
    app.util.navigateTo(url);
  },

  // 收藏的逻辑 列表收藏在本地，把当前在线循环对比一下，在本地的塞进一个在线列表
  collectCard(e) {
    const { cardid } = e.currentTarget.dataset;
    let cards = this.data.collectedItems.push(cardid);
  },

  // 索引滚动方案
  scrollTo(e) {
    let toView = e.currentTarget.dataset.id;
    this.setData({
      toView,
    });
  },

  reportFormID(e) {
    e.detail.formId && _util.sendFormID(e.detail.formId);
  },
});

